<?php



class OpenApi extends ApiBase{


	/**
	 * 构造函数，初始化插件
	 */
	public function __construct() {
		parent::__construct();
	}

	public function getPboxApi($pboxId){
		return n_api("mysql")->db001->selectIndex("select * from open_api where main_id={$pboxId}");
	}
	
	/**
	 * 添加记录
	 */
	public function log($ppid,$apiId,$descript){
		$data['ppid'] = $ppid;
		$data['api_id'] = $apiId;
		$data['descript'] = $descript;
		$data['ctime'] = time();
		n_api('mysql')->db001->insert("open_log",$data);
		return true;
	}
	
	public function getLog($limit=1000000){
		return n_api('mysql')->db001->select("select a.*,b.paction as api_action,b.title as api_title,b.main_id as pevent_id from open_log as a
													left join open_api as b on a.api_id=b.id
													order by id desc limit {$limit}");
	}

	/**
	 * 仅支持-1删除,2通过,3恢复
	 * 
	 */
	private function update($scode,$id,$uid,$state){
		$nsite = n_api("nsite");
		$antidata = n_api("antidata");
		$passport = n_api("passport");

		$nsiteInfo = $nsite->getByScode($scode);//站点信息
		$dataInfo = $antidata->getdetail($scode, $id);//文章信息
		$userInfo = $passport->get($uid);//操作人信息
		
		switch ($state) {
			case '-1':
				$stateStr = 'del';
				break;
			case '2':
				$stateStr = 'pass';
				if(($dataInfo['main']['state'] == $dataInfo['main']['ocode']) && ($dataInfo['main']['ucode'] == 0) ){
					//两边数据一致不用向站点发送指令.
					// echo "\n--this--\n";
					// return array('state'=>true);
				}
				break;
			case '3':
				$stateStr = 'recover';
				break;
			default:
				throw new PException("非法的状态请求", 2004);
				break;
		}
		

		$data['cmd'] = "article";
		//签名还需要改
		$data['sign'] = md5($nsiteInfo['sign'].':'.trim($dataInfo['main']['url']));

		$data['request'] = json_encode(array(
							'state'=>$stateStr,			//只存在过河不过的状态[pass,del]
							'url'=> $dataInfo['main']['url'],//sunjian@20121229添加文章url 和图片接口格式统一
							'source_id'=>$dataInfo['main']['source_id'],
							'callback'=>empty($dataInfo['data']['callback'])?array():json_decode($dataInfo['data']['callback'],true)
		));
		
		$data['audit']=json_encode(array(
							'uname'=>$userInfo['uname'],
							'ip'=>n_api('common')->getClientIp(),
							'uid'=>$userInfo['id']
		));

		// if(!empty($sub['out_domain'])){
		// 	$rs = api("common")->curlPost($sub['out_url'],$data,$sub['out_port'],$sub['out_domain']);
		// }

		$rs = n_api("common")->curlPost($nsiteInfo['api_url'],$data);

		if(in_array($nsiteInfo['charset'], array(2,3))){//2=gbk,3=GB18030
			$rs['respond'] = iconv("GBK", "UTF-8", $rs['respond']);
		}

		// echo "<pre>";
		// var_dump($nsiteInfo['api_url']);
		// var_export($data);
		// echo "\n";
		// echo http_build_query($data);
		// echo "\n";
		// var_export($rs);
		// echo '=======';
		// echo $rs['respond'].'----------------------';
		
		$respond = json_decode($rs['respond'],true);
		//print_r($respond);
		if(!isset($respond['state'])){ 
			throw new PException("错误的响应数据:{$rs['respond']}", 2005);
		}
		
		if(!$respond['state'] || 'false'==strtolower($respond['state'])){
			throw new PException("请求失败:{$respond['msg']}", 2006);
		}
		/*
		print_r($rs);
		print_r($data);
		print_r($respond);

		 */
		//exit;
		return $respond;
	}

	private function del($scode,$id,$uid){
		if ($scode <> 'f3680dc664570431') {
			return n_state(TRUE, "删除成功");
		}

		return $this->update($scode, $id, $uid, -1);
	}

	private function recover($scode,$id,$uid){
		if ($scode <> 'f3680dc664570431') {
			return n_state(TRUE, "通过成功");
		}
		
		return $this->update($scode, $id, $uid, 3);
	}

	private function pass($scode,$id,$uid){
		if ($scode <> 'f3680dc664570431') {
			return n_state(TRUE, "通过成功");
		}

		return $this->update($scode, $id, $uid, 2);
	}

	public function sendCmd($scode,$id,$uid,$cmd){

		try{

			if (empty($scode) || empty($id) || empty($uid) || empty($cmd)) {
				throw new PException("回调接口参数错误",2001);
			}
			
			$nsiteInfo = n_api("nsite")->getByScode($scode);

			if (empty($nsiteInfo)) {
				throw new PException("站点信息错误",2002);
			}

			if (!in_array($cmd, array('pass', 'del', 'recover'))) {
				throw new PException("回调接口命令错误",2003);
			}

			$rs = $this->$cmd($scode,$id,$uid);

			return $rs;

		}catch (Exception $e) {
			$tmp = array("scode"=>$scode,
						"main_id"=>$id,
						"ppid"=>$uid,
						"cmd"=>$cmd,
						"ecode"=>$e->getCode(),
						"emsg"=>$e->getMessage(),
						);
			
			n_api("nlog")->add($scode,'open_callback',$e->getMessage(),$tmp);
		}
	}


}